import { useEffect, useState } from "react";
import { getConnectionApi, getDatabaseApi, getToken } from "./utils/client"
import { Button, Card, List, Popover, Space, message } from "antd"
import { MoreOutlined, PlusOutlined } from "@ant-design/icons";
import classNames from "classnames";
import s from "./common.module.less";
import ConnModal from "./components/ConnModal";
import { getMinAppInfo } from "@linksaas-minapp/api";


export interface DatabaseListProps {
    onChange: (clientId: string, database: string) => void;
}

interface ClientInfo {
    id: string;
    name: string;
    dataSource: string;
}


function DatabaseList(props: DatabaseListProps) {
    const [clientList, setClientList] = useState<ClientInfo[]>([]);
    const [curClientId, setCurClientId] = useState("");
    const [dbList, setDbList] = useState<string[]>([]);
    const [curDb, setCurDb] = useState("");

    const [showConnModal, setShowConnModal] = useState(false);

    const loadClient = async () => {
        setCurClientId("");
        setDbList([]);
        setCurDb("");
        const client = getConnectionApi();
        const res = await client.connectionListPost({
            connectionListPostRequest: {
                token: getToken(),
            },
        });
        setClientList(res.map(item => ({
            id: item.id ?? "",
            name: item.name ?? "",
            dataSource: item.dataSource ?? "",
        })));
    };

    const removeClient = async (id: string) => {
        const client = getConnectionApi();
        await client.connectionClosePost({
            connectionClosePostRequest: {
                token: getToken(),
                id,
            },
        });
        if (id == curClientId) {
            setCurClientId("");
            setDbList([]);
            setCurDb("");
        }
        const tmpList = clientList.filter(item => item.id !== id);
        setClientList(tmpList);
    };

    const loadDatabase = async () => {
        setDbList([]);
        setCurDb("");
        const client = getDatabaseApi();
        try {
            const res = await client.databaseListPost({
                databaseListPostRequest: {
                    token: getToken(),
                    id: curClientId,
                },
            });
            setDbList(res);
        } catch (e) {
            console.log(e);
            message.error("权限不足，无法列出数据库");
        }

    };

    useEffect(() => {
        loadClient();
    }, []);

    useEffect(() => {
        if (curClientId != "") {
            loadDatabase();
        }
    }, [curClientId]);

    useEffect(() => {
        props.onChange(curClientId, curDb);
    }, [curClientId, curDb]);

    useEffect(() => {
        const minAppInfo = getMinAppInfo();
        if (minAppInfo != undefined && minAppInfo.extraInfo != undefined && minAppInfo.extraInfo.length > 0) {
            setShowConnModal(true);
        }
    }, []);

    return (
        <div>
            <Card bordered={false}
                style={{ height: "50vh", overflow: "hidden" }} bodyStyle={{ height: "calc(50vh - 60px)", overflowY: "auto" }}
                title="数据库连接" extra={
                    <Space>
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowConnModal(true);
                            }}><PlusOutlined /></Button>
                    </Space>
                }>
                <List dataSource={clientList} renderItem={item => (
                    <List.Item key={item.id} extra={
                        <Popover trigger="click" placement="bottom" content={
                            <div>
                                <Button type="link" onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    removeClient(item.id);
                                }}>断开连接</Button>
                            </div>
                        }>
                            <MoreOutlined />
                        </Popover>
                    } className={classNames(s.item, curClientId == item.id ? s.active : "")} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setCurClientId(item.id);
                    }}>
                        <div className={s.name} title={`${item.name}(${item.dataSource})`}>{item.name}</div>
                    </List.Item>
                )} />
            </Card>
            <Card bordered={false}
                style={{ height: "50vh", overflow: "hidden" }} bodyStyle={{ height: "calc(50vh - 60px)", overflowY: "auto" }}
                title="DB列表">
                <List dataSource={dbList} renderItem={item => (
                    <List.Item key={item} className={classNames(s.item, curDb == item ? s.active : "")} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setCurDb(item);
                    }}>
                        <div className={s.name}>{item}</div>
                    </List.Item>
                )} />
            </Card>
            {showConnModal == true && (
                <ConnModal onCancel={() => setShowConnModal(false)}
                    onOk={(id, name, dataSource) => {
                        const tmpList = clientList.slice();
                        tmpList.push({
                            id, name, dataSource,
                        });
                        setClientList(tmpList);
                        setShowConnModal(false);
                    }} />
            )}
        </div>


    );
}

export default DatabaseList;